import JSZip from "jszip";
import { saveAs } from "file-saver"; // 注意这里我假设你已经有file-saver库了
interface FileData {
	url: string;
	name: string;
}
const useZip = (isCompress = false, compressionLevel = 6) => {
	const buildZipDownload = (fileDatas: FileData[]) => {
		return new Promise((resolve, reject) => {
			const zip = new JSZip();
			let promises = [];
			for (let item of fileDatas) {
				if (item.url) {
					const promise = getImgArrayBuffer(item.url).then(
						(data: any) => {
							zip.file(item.name, data, {
								binary: true,
							});
						}
					);
					promises.push(promise);
				} else {
					alert(`附件${item.name}地址错误，下载失败`);
				}
			}
			Promise.all(promises)
				.then(async () => {
					let content: Blob;
					if (isCompress) {
						content = await zip.generateAsync({
							type: "blob",
							compression: "DEFLATE",
							compressionOptions: { level: compressionLevel },
						});
					} else {
						content = await zip.generateAsync({ type: "blob" });
					}
					resolve(content); // 利用file-saver保存文件  blogTitle:自定义文件名
				})
				.catch((res) => {
					console.log(res);
					uni.showModal({
						title: "提示",
						content: "下载失败，请稍后重试",
						showCancel: false,
						confirmText: "确定",
						confirmColor: "B41732",
					});
					reject(res);
				});
		});
	};
	return {
		buildZipDownload,
	};
};

const getImgArrayBuffer = (url: string) => {
	return new Promise((resolve, reject) => {
		//通过请求获取文件blob格式
		uni.request({
			url,
			method: "GET",
			responseType: "arraybuffer",
			success: (res) => {
				const blob = new Blob([res.data as unknown as ArrayBuffer], {
					type: "application/octet-stream;charset=UTF-8",
				});
				if (res.statusCode == 200) {
					resolve(blob);
				} else {
					reject(blob);
				}
			},
		});
	});
};
export { useZip };
